import { mockRequestClient } from '#/api/request';

// 接口定义
export interface RboInvokeRequest {
  input: Record<string, any>;
  context?: {
    tenantId?: string;
    userId?: string;
    traceId?: string;
  };
}

export interface RboInvokeResponse {
  status: 'accepted' | 'completed' | 'failed';
  output?: Record<string, any>;
  eventIds?: string[];
  state?: string;
  error?: string;
}

export interface BehaviorDef {
  id: string;
  name: string;
  resourceType: string;
  inputSchema?: Record<string, any>;
  outputSchema?: Record<string, any>;
  preconditions?: Array<{
    type: string;
    value: any;
  }>;
  impl: {
    type: 'bpm' | 'orchestration' | 'service' | 'rule';
    ref: string;
    timeoutSec?: number;
  };
  sla?: {
    retry?: number;
    compensation?: string;
    timeout?: number;
  };
}

export interface EventDef {
  id: string;
  name: string;
  resourceType: string;
  payloadSchema?: Record<string, any>;
  channel?: string;
}

export interface StateMachineDef {
  states: string[];
  transitions: Array<{
    from: string;
    to: string;
    by: string;
  }>;
}

// 性能优化：请求缓存
const cache = new Map<string, { data: any; timestamp: number; ttl: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5分钟缓存

// 缓存工具函数
const getCacheKey = (url: string, params?: any) => {
  return `${url}${params ? JSON.stringify(params) : ''}`;
};

const getCachedData = (key: string) => {
  const cached = cache.get(key);
  if (cached && Date.now() - cached.timestamp < cached.ttl) {
    return cached.data;
  }
  if (cached) {
    cache.delete(key);
  }
  return null;
};

const setCachedData = (key: string, data: any, ttl: number = CACHE_TTL) => {
  cache.set(key, { data, timestamp: Date.now(), ttl });
};

// 清理过期缓存
const cleanupCache = () => {
  const now = Date.now();
  for (const [key, value] of cache.entries()) {
    if (now - value.timestamp > value.ttl) {
      cache.delete(key);
    }
  }
};

// 定期清理缓存
setInterval(cleanupCache, 60000); // 每分钟清理一次

// RBO API客户端
export const rboApi = {
  // 调用行为
  async invokeBehavior(
    resourceType: string,
    resourceId: string,
    behaviorName: string,
    request: RboInvokeRequest,
  ): Promise<RboInvokeResponse> {
    const cacheKey = getCacheKey(
      `invoke_${resourceType}_${resourceId}_${behaviorName}`,
      request,
    );
    const cached = getCachedData(cacheKey);
    if (cached) {
      return cached;
    }

    const response = await mockRequestClient.post(
      `/rbo/${resourceType}/${resourceId}/behaviors/${behaviorName}/invoke`,
      request,
    );

    setCachedData(cacheKey, response, 30000); // 30秒缓存
    return response;
  },

  // 获取行为定义列表
  async getBehaviors(resourceType?: string): Promise<BehaviorDef[]> {
    const cacheKey = getCacheKey('behaviors', { resourceType });
    const cached = getCachedData(cacheKey);
    if (cached) {
      return cached;
    }

    const params = resourceType ? { resourceType } : {};
    const response = await mockRequestClient.get('/rbo/behaviors', { params });

    setCachedData(cacheKey, response, CACHE_TTL);
    return response;
  },

  // 获取状态机定义
  async getStateMachine(resourceType: string): Promise<StateMachineDef> {
    const cacheKey = getCacheKey(`state-machine_${resourceType}`);
    const cached = getCachedData(cacheKey);
    if (cached) {
      return cached;
    }

    const response = await mockRequestClient.get(
      `/rbo/${resourceType}/state-machine`,
    );

    setCachedData(cacheKey, response, CACHE_TTL);
    return response;
  },

  // 获取资源当前状态
  async getResourceState(
    resourceType: string,
    resourceId: string,
  ): Promise<{ state: string }> {
    const cacheKey = getCacheKey(`state_${resourceType}_${resourceId}`);
    const cached = getCachedData(cacheKey);
    if (cached) {
      return cached;
    }

    const response = await mockRequestClient.get(
      `/rbo/${resourceType}/${resourceId}/state`,
    );

    setCachedData(cacheKey, response, 10000); // 10秒缓存
    return response;
  },

  // 状态转换
  async transitionState(
    resourceType: string,
    resourceId: string,
    fromState: string,
    toState: string,
    reason?: string,
  ): Promise<{ success: boolean; newState: string }> {
    const response = await mockRequestClient.post(
      `/rbo/${resourceType}/${resourceId}/state/transition`,
      {
        from: fromState,
        to: toState,
        reason,
      },
    );

    // 状态变更后清除相关缓存
    const stateCacheKey = getCacheKey(`state_${resourceType}_${resourceId}`);
    cache.delete(stateCacheKey);

    return response;
  },

  // 获取状态历史
  async getStateHistory(
    resourceType: string,
    resourceId: string,
  ): Promise<
    Array<{
      state: string;
      timestamp: string;
      reason: string;
    }>
  > {
    const cacheKey = getCacheKey(`history_${resourceType}_${resourceId}`);
    const cached = getCachedData(cacheKey);
    if (cached) {
      return cached;
    }

    const response = await mockRequestClient.get(
      `/rbo/${resourceType}/${resourceId}/state/history`,
    );

    setCachedData(cacheKey, response, 30000); // 30秒缓存
    return response;
  },

  // 发布事件
  async publishEvent(
    eventName: string,
    payload: any,
  ): Promise<{ eventId: string }> {
    const response = await mockRequestClient.post('/rbo/events/publish', {
      name: eventName,
      payload,
    });

    return response;
  },

  // 订阅事件
  async subscribeToEvent(
    eventName: string,
    callback: (payload: any) => void,
  ): Promise<void> {
    // 这里可以实现WebSocket或其他事件订阅机制
    console.log(`订阅事件: ${eventName}`);
  },

  // 行为定义CRUD
  async createBehavior(
    behavior: Omit<BehaviorDef, 'id'>,
  ): Promise<BehaviorDef> {
    const response = await mockRequestClient.post('/rbo/behaviors', behavior);

    // 清除行为列表缓存
    const behaviorsCacheKey = getCacheKey('behaviors');
    cache.delete(behaviorsCacheKey);

    return response;
  },

  async updateBehavior(
    id: string,
    behavior: Partial<BehaviorDef>,
  ): Promise<BehaviorDef> {
    const response = await mockRequestClient.put(
      `/rbo/behaviors/${id}`,
      behavior,
    );

    // 清除相关缓存
    const behaviorsCacheKey = getCacheKey('behaviors');
    cache.delete(behaviorsCacheKey);

    return response;
  },

  async deleteBehavior(id: string): Promise<void> {
    await mockRequestClient.delete(`/rbo/behaviors/${id}`);

    // 清除行为列表缓存
    const behaviorsCacheKey = getCacheKey('behaviors');
    cache.delete(behaviorsCacheKey);
  },

  // 事件定义CRUD
  async createEvent(event: Omit<EventDef, 'id'>): Promise<EventDef> {
    const response = await mockRequestClient.post(
      '/rbo/events/definitions',
      event,
    );

    // 清除事件定义缓存
    const eventsCacheKey = getCacheKey('events/definitions');
    cache.delete(eventsCacheKey);

    return response;
  },

  async updateEvent(id: string, event: Partial<EventDef>): Promise<EventDef> {
    const response = await mockRequestClient.put(
      `/rbo/events/definitions/${id}`,
      event,
    );

    // 清除事件定义缓存
    const eventsCacheKey = getCacheKey('events/definitions');
    cache.delete(eventsCacheKey);

    return response;
  },

  async deleteEvent(id: string): Promise<void> {
    await mockRequestClient.delete(`/rbo/events/definitions/${id}`);

    // 清除事件定义缓存
    const eventsCacheKey = getCacheKey('events/definitions');
    cache.delete(eventsCacheKey);
  },

  // 获取事件定义列表
  async getEventDefinitions(resourceType?: string): Promise<EventDef[]> {
    const cacheKey = getCacheKey('events/definitions', { resourceType });
    const cached = getCachedData(cacheKey);
    if (cached) {
      return cached;
    }

    const params = resourceType ? { resourceType } : {};
    const response = await mockRequestClient.get('/rbo/events/definitions', {
      params,
    });

    setCachedData(cacheKey, response, CACHE_TTL);
    return response;
  },

  // 清除所有缓存
  clearCache(): void {
    cache.clear();
  },

  // 获取缓存统计信息
  getCacheStats(): { size: number; keys: string[] } {
    return {
      size: cache.size,
      keys: Array.from(cache.keys()),
    };
  },
};
